package com.al.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns="/download")
public class DownloadServlet extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String type = req.getParameter("type");
		String fileName = "";
		switch(type) {
		case "png":
			fileName = "1.PNG";
			break;
		case "txt":
			fileName = "test.txt";
			break;
		}
		//设置响应方式（启动浏览器的下载器）
		resp.setContentType("application/x-msdownload");
		//设置下载之后的文件名
		resp.setHeader("Content-Disposition", "attachment;filename="+fileName);
		/*上面的这些，除了文件名都是写死的*/
		
		//获取输出流
		OutputStream outputStream = resp.getOutputStream();
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
		//获取资源的绝对路径
		//这文件的后缀名大小写一定要一样，一定要一样，一定要一样，别问我为什么（我的眼里常含泪水)
		String path = req.getServletContext().getRealPath("file/"+fileName);
		
		//创建字节流，先把图片读到程序内存中
		InputStream inputStream = new FileInputStream(path);
		BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
		int temp = 0;
		while((temp = bufferedInputStream.read()) != -1) {
			bufferedOutputStream.write(temp);
		}
		bufferedOutputStream.flush();
		bufferedOutputStream.close();
		outputStream.close();
		bufferedInputStream.close();
		inputStream.close();
	}
}
